package com.smmisia.article.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smmisia.article.api.AuthService;
import com.smmisia.article.dto.user.UserVO;
import com.smmisia.article.entity.Comment;
import com.smmisia.article.entity.User;
import com.smmisia.article.entity.convetor.CommentConvertor;
import com.smmisia.article.entity.convetor.UserConvertor;
import com.smmisia.article.exception.customException;
import com.smmisia.article.mapper.UserMapper;
import com.smmisia.article.request.CommentAddRequest;
import com.smmisia.article.response.commentResponse;
import com.smmisia.article.service.CommentService;
import com.smmisia.article.mapper.CommentMapper;
import com.smmisia.article.vo.CommentVO;
import com.smmisia.common.Result.Result;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthService authService;

    private final String PREFIX = "ip:";

    @Override
    public Result<List<commentResponse>> commentList(int articleId, int type) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getTargetId, articleId);
        wrapper.eq(Comment::getType, type);
        wrapper.orderByDesc(Comment::getCreateTime);
        List<Comment> list = commentMapper.selectList(wrapper);

        // 存储所有评论的ID和评论对象
        Map<Integer, Comment> commentMap = list.stream().collect(Collectors.toMap(Comment::getId, comment -> comment));

        // 用于构建树形结构的回复列表
        Map<Integer, List<commentResponse>> replyMap = new HashMap<>();

        // 遍历所有评论并构建replyList
        ArrayList<commentResponse> responses = new ArrayList<>();
        list.forEach(comment -> {
            Integer userId = comment.getUserId();
            Integer toUserId = comment.getToUserId();

            // 获取评论者信息
            User user = authService.info(userId);
            UserVO userVO = UserConvertor.INSTANCE.mapToUserVO(user);
            if(user != null){
                String ipAddress = (String) redisTemplate.opsForValue().get(PREFIX + userId);
                userVO.setAddress(ipAddress);
            }
            // 获取被回复者信息（如果有的话）
            User toUser = (toUserId != null) ? authService.info(toUserId) : null;
            UserVO toUserVO = (toUser != null) ? UserConvertor.INSTANCE.mapToUserVO(toUser) : null;
            if(toUser != null){
                String ipAddress = (String) redisTemplate.opsForValue().get(PREFIX + toUserId);
                toUserVO.setAddress(ipAddress);
            }

            // 创建commentResponse对象
            commentResponse response = new commentResponse();
            CommentVO commentVO = CommentConvertor.INSTANCE.mapToCommentVO(comment);
            response.setCommentVO(commentVO); // 假设 CommentVO 是你要返回的评论视图对象
            response.setUserInfo(userVO);
            response.setToUserInfo(toUserVO);
            response.setReplyList(new ArrayList<>());

            // 如果是子评论，添加到父评论的replyList
            Integer parentId = comment.getPid();
            if (parentId == 0) {
                responses.add(response);
            } else {
                replyMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(response);
            }
        });

        // 将每个父评论的replyList补充完整
        responses.forEach(response -> {
            Integer parentId = response.getCommentVO().getId();
            if (replyMap.containsKey(parentId)) {
                response.setReplyList(replyMap.get(parentId));
            }
        });

        return Result.ok(responses);
    }

    @Override
    public Result<String> add(CommentAddRequest request) {
        Comment comment = Comment.create(request);
        boolean save = this.save(comment);
        Assert.isTrue(save,()->new customException("发布评论失败"));
        return Result.ok("发布成功");
    }

    @Override
    public Result<String> delete(int id) {
        String loginId = (String) StpUtil.getLoginId();
        Integer userId = Integer.valueOf(loginId);
        LambdaUpdateWrapper<Comment> wrapper = new LambdaUpdateWrapper<Comment>();
        wrapper.eq(Comment::getUserId, userId)
                .eq(Comment::getId, id);
        int result = commentMapper.delete(wrapper);
        Assert.isTrue(result == 1, ()->new customException("删除失败"));
        return Result.ok("删除成功");
    }

    @Override
    public Result<String> like(int id) {
        String loginId = (String) StpUtil.getLoginId();
        //TODO 存在重复点赞问题
        LambdaUpdateWrapper<Comment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Comment::getId, id);
        wrapper.setSql("likes_count = likes_count + 1");
        int result = commentMapper.update(null, wrapper);
        Assert.isTrue(result == 1, ()->new customException("点赞失败"));
        return Result.ok("点赞成功");
    }

}




